<template>
  <ContentWrap>
    <fromTitle
      title="甲方单位管理"
      :queryParams="queryParams"
      @search="getList"
      @reset="resetQuery"
      :hasPermi="'qis:first-party:query'"
    />

    <!-- 搜索工作栏 -->
    <div style="height: 80px">
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
       
      >
        <el-form-item inline label-width="150" label="组织机构名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入组织机构名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item label="简称" prop="shortName">
          <el-input
            v-model="queryParams.shortName"
            placeholder="请输入简称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>



        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            class="!w-240px"
          >
            <el-option label="活动" value="0" />
            <el-option label="不活动" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label-width="100" label="组织机构级别" prop="levelValue">
          <el-select
            v-model="queryParams.levelValue"
            placeholder="请选择组织机构级别"
            clearable
            class="!w-240px"
          >
            <el-option label="集团" value="0" />
            <el-option label="板块" value="1" />
            <el-option label="企业" value="2" />
            <el-option label="二级单位" value="3" />
            <el-option label="基层单位" value="4" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="table-btn">
      <el-button type="warning" v-hasPermi="['qis:first-party:create']"  @click="handleAdd">新增</el-button>
      <el-button type="info" v-hasPermi="['qis:first-party:export']" @click="handleExport">导出</el-button>
      <el-button type="danger" v-hasPermi="['qis:first-party:delete']" @click="handleDelete">删除</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
    <el-table-column width="55">
        <template #header>
          <span>选择</span>
        </template>
        <template #default="scope">
          <el-checkbox v-model="scope.row.selected" @change="handleSelect(scope.row)"/>
        </template>
      </el-table-column>

      <el-table-column label="简称" align="center" prop="shortName" />
      <el-table-column label="组织机构名称" align="center" prop="name">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row.id)">{{
            `${scope.row.name}${scope.row.status !== 0 ? `(已失效)`:''}`
          }}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="上层组织机构" align="center" prop="parentName" />
      <!-- <el-table-column label="上层组织机构" align="center" prop="id" /> -->
      <el-table-column label="路径全称" align="center" prop="pathAllName" />
      <el-table-column label="状态" align="center" prop="id">
        <template #default="scope">
          <span v-if="scope.row.status === 0">活动</span>
          <span v-else>不活动</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrganizationQualificationForm title="" ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

import OrganizationQualificationForm from './OrganizationQualificationForm.vue'
import { firstPartyApi } from '@/api/qis/firstParty'
import download from '@/utils/download'

const router = useRouter()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  type: undefined,
  num: undefined,
  licenceIssuingAuthority: undefined,
  issueDate: [],
  expireTime: [],
  attachment: undefined,
  orgId: undefined,
  status: undefined,
  orgLevel: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const rules = reactive({
  shortName: [{ required: true, message: '请输入简称', trigger: 'blur' }],
  orgLevel: [{ required: true, message: '请选择组织机构级别', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  name: [{ required: true, message: '请选择组织机构名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' },{ pattern: /^\d+$/, message: '排序必须为数字', trigger: 'blur' },{max:8, message: '排序不能超过8位', trigger: 'blur' }]
})


 const arrayList = ref([])

const handleSelect = (row ) => {
  // console.log('删除指标要求', row)
  if(row.selected){
    arrayList.value.push(row.id)
    console.log(arrayList.value,'arrayList.value')
  }else {
    arrayList.value.splice(arrayList.value.indexOf(row.id),1)
    console.log(arrayList.value,'arrayList.value')
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await firstPartyApi.getfirstPartyPage(queryParams)
    // list.value = data.list

    list.value = data.list
    list.value.forEach(item=>{
      item.selected = false
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加按钮操作 */
const handleAdd = () => {
  router.push('/inspection-info-management/party-management/add')
}

/** 详情按钮操作 */
const handleDetail = (id: number) => {
  router.push('/inspection-info-management/party-management/add?id=' + id)
}

/** 删除按钮操作 */
const handleDelete = async () => {
  try {
    if (arrayList.value.length > 0) {
      ElMessageBox.confirm('确定删除选中数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
      // 删除的二次确认
      // await message.delConfirm()
      // 发起删除
      const ids = arrayList.value.join(';')
      await firstPartyApi.deletefirstParty(ids)
      message.success(t('common.delSuccess'))
      // 刷新列表
      arrayList.value = []
       getList()
      }).catch(() => {
      })
    } else {
      message.error(t('请选择要删除的数据'))
    }
  } catch(err) {
    console.log("🚀 ~ handleDelete ~ err:", err)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  if(total.value > 10000) return message.error('当前数据过大，请筛选数据后导出')
  try {
    if(arrayList.value.length > 0) {
      await message.exportConfirm()
      const idsArr = arrayList.value.join(';') 
        // 发起导出
    exportLoading.value = true

const data = await firstPartyApi.exportfirstParty({ids:idsArr,...queryParams})
download.excel(data, '质检平台-甲方单位管理.xls')
    }else {
  // 导出的二次确认
  await message.exportConfirm()
    // 发起导出
    exportLoading.value = true

    const data = await firstPartyApi.exportfirstParty(queryParams)
    download.excel(data, '质检平台-甲方单位管理.xls')
    }
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// const selectedList = ref<number[]>([])
// const handleSelect = (row: any) => {
//   selectedList.value = row
// }

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.table-btn {
  padding: 10px 50px;
}
</style>
